package com.xuzhiguang.light.gateway.startup;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

/**
 * @author xuzhiguang
 */
@Slf4j
public class GatewayConfigLoader {

    private static final String PROPERTIES_FILE = "light-gateway.properties";

    private static final String CONFIG_ENV_PREFIX = "LIGHT_G_";

    private static final String CONFIG_JVM_PREFIX = "light_g.";

    private static final GatewayConfigLoader INSTANCE = new GatewayConfigLoader();

    private GatewayConfigLoader() {

    }

    public static GatewayConfigLoader getInstance() {
        return INSTANCE;
    }

    public Properties load(String[] args) {

        Properties properties = new Properties();

        loadFile(PROPERTIES_FILE, properties);

        loadEnv(CONFIG_ENV_PREFIX, properties);

        loadJVM(CONFIG_JVM_PREFIX, properties);

        loadArgs(args, properties);

//        loadDynamicConfig(null, properties);

        return properties;
    }

    private void loadFile(String file, Properties properties) {

        try (InputStream input = this.getClass().getClassLoader().getResourceAsStream(file)) {
            properties.load(input);
        } catch (IOException e) {
            log.error("[GatewayConfigLoader] load config file error, file:{}", file, e);
        }
    }


    private void loadEnv(String prefix, Properties properties) {

        Map<String, String> env = System.getenv();

        env.forEach((s, s2) -> {
            if (s.startsWith(prefix)) {
                String key = s.substring(prefix.length());

                properties.put(key, s2);
            }
        });
    }

    private void loadJVM(String prefix, Properties properties) {

        Properties systemProperties = System.getProperties();

        systemProperties.forEach((o, o2) -> {
            String s = o.toString();
            if (s.startsWith(prefix)) {
                String key = s.substring(prefix.length());

                properties.put(key, o2);
            }
        });
    }

    private void loadArgs( String[] args, Properties properties) {
        if(args != null && args.length > 0) {
            for(String arg : args) {
                if(arg.startsWith("--") && arg.contains("=")) {
                    properties.put(arg.substring(2, arg.indexOf("=")), arg.substring(arg.indexOf("=") + 1));
                }
            }
        }
    }


}
